import 'dart:io';

import 'package:sqflite/sqflite.dart';
import 'jvtd_sqflite_print.dart';

mixin JvtdDatabase {
  static const String _DB_TAG = '数据库';

  String get dbName; //数据库名称

  int get version; //当前版本

  List<int> get oldVersions; //老版本集合

  Database _database; //数据库实体

  // 获取当前数据库
  Database get database {
    if (_database == null) {
      _log('数据库未初始化！');
    }
    return _database;
  }

  /// 数据库初始化
  Future<bool> init() async {
    //获取路径
    var databasesPath = await getDatabasesPath();
    // Make sure the directory exists
    try {
      await Directory(databasesPath).create(recursive: true);
    } catch (_) {
      _log(_.toString());
    }
    //拼接路径
    String path = databasesPath + '/' + dbName;
    _log("数据库地址：" + path);
    //创建数据库
    try {
      var jvtdDb = await openDatabase(
        path,
        version: version,
        onCreate: (db, version) async {
          var batch = db.batch();
          onCreate(batch, version);
          await batch.commit();
          _log("数据库-表-创建完成");
        },
        onUpgrade: (db, oldVersion, newVersion) async {
          var batch = db.batch();
          onUpdate(batch, oldVersion, newVersion, oldVersions);
          await batch.commit();
          _log("数据库-表-更新完成");
        },
        onDowngrade: onDatabaseDowngradeDelete,
        onOpen: (db) {
          _database = db;
          _log("打开数据库");
          onComplete();
        },
      ).catchError((e) {
        _log(e);
        return false;
      });
      return jvtdDb != null;
    } catch (e) {
      _log(e);
      return false;
    }
  }

  // 数据库打印工具
  void _log(Object data) {
    sqfliteLog(_DB_TAG, '[$dbName]', data);
  }

  /// 数据库创建成功回调
  void onCreate(Batch batch, int version);

  /// 数据库更新成功回调
  void onUpdate(Batch batch, int oldVersion, int newVersion, List<int> oldVersions);

  /// 数据库完成回调
  void onComplete();
}
